package com.huiminpay.merchant.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class SmsServiceImpl implements com.huiminpay.merchant.service.SmsService {

    @Value("${sms.url}")
    String smsUrl;
    @Value("${sms.effectiveTime}")
    String smsEffectiveTime;
    @Autowired
    RestTemplate restTemplate;
    @Override
    public String sendSms(String mobile) {
        String url =smsUrl+"/generate?effectiveTime="+smsEffectiveTime+"&name=sms";
        String phone = "13460308745";
        //请求体
        Map<String, Object > map = new HashMap();
        map.put("mobile", phone);
        //封装请求参数
        HttpEntity entity = new HttpEntity(map);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        String body = exchange.getBody();

        //通过fastjson解析  解析成json 拿到result的值
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONObject result = jsonObject.getJSONObject("result");

        return result.getString("key");

    }

    @Override
    public Boolean verifyCode(String code, String key) {
        String url = smsUrl+"/verify?name=sms&verificationCode="+code+"&verificationKey="+key;
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, null, String.class);
        String body = exchange.getBody();
        //通过fastjson解析  解析成json 拿到result的值
        JSONObject jsonObject = JSONObject.parseObject(body);
        return jsonObject.getBoolean("result");
    }
}
